package com.xin.di.uav.applet.controller;

import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.partnerpayments.h5.model.Transaction;
import com.xin.di.uav.applet.service.OrderService;
import com.xin.di.uav.common.enums.PayStatusEnum;
import com.xin.di.uav.common.request.order.task.ConfirmPayRequest;
import com.xin.di.uav.mapper.BillMapper;
import com.xin.di.uav.po.Bill;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@RestController
@RequestMapping("/home/wx-pay")
@Slf4j
public class WxPayCallbackController {
    @Autowired
    private WxPayConfig config;

    @Autowired
    private OrderService orderService;
    @Autowired
    private BillMapper billMapper;

    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) {
        log.warn("进来啦");
        try {
            // 1. 获取回调报文
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String signature = request.getHeader("Wechatpay-Signature");
            String serial = request.getHeader("Wechatpay-Serial");
            String body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);

            // 2. 构造验签参数

            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(serial)    // 微信支付证书序列号
                    .nonce(nonce)            // 随机字符串
                    .signature(signature)    // 微信回调签名
                    .timestamp(timestamp)    // 时间戳
                    .body(body)              // 回调报文主体
                    .build();

            // 3. 验签并解密
            NotificationParser parser = new NotificationParser(config.getConfig());
            Transaction transaction = parser.parse(requestParam, Transaction.class);

            // 4. 处理业务逻辑
            if ("SUCCESS".equals(transaction.getTradeState().name())) {
                log.warn("验签成功");
                ConfirmPayRequest confirmPayRequest = new ConfirmPayRequest();
                confirmPayRequest.setTradeNo(transaction.getOutTradeNo());
                confirmPayRequest.setTransactionId(transaction.getTransactionId());
                orderService.confirmPay(confirmPayRequest);
                return "{\"code\": \"SUCCESS\", \"message\": \"成功\"}";
            }
        } catch (Exception e) {
            return "{\"code\": \"FAIL\", \"message\": \"处理失败\"}";
        }
        return null;
    }


    @PostMapping("/refund-notify")
    public String refundNotify(HttpServletRequest request) {
        log.warn("进来啦,退款回调接口");
        try {
            // 1. 获取回调报文
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String signature = request.getHeader("Wechatpay-Signature");
            String serial = request.getHeader("Wechatpay-Serial");
            String body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
            log.warn("进来啦,退款回调接口1" + body);
            // 2. 构造验签参数

            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(serial)    // 微信支付证书序列号
                    .nonce(nonce)            // 随机字符串
                    .signature(signature)    // 微信回调签名
                    .timestamp(timestamp)    // 时间戳
                    .body(body)              // 回调报文主体
                    .build();
            log.warn("进来啦,退款回调接口2" + requestParam);
            // 3. 验签并解密
            NotificationParser parser = new NotificationParser(config.getConfig());
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            log.warn("进来啦,退款回调接口3" + transaction);
            String outTradeNo = transaction.getOutTradeNo();
            if (!ObjectUtils.isEmpty(outTradeNo)) {
                Bill bill = billMapper.selectRefundPending(outTradeNo);
                if (!ObjectUtils.isEmpty(bill)) {
                    bill.setUpdateTime(new Date());
                    bill.setPayStatus(PayStatusEnum.REFUND.getValue());
                    billMapper.updateStatus(bill);
                }
            }

        } catch (Exception e) {
            return "{\"code\": \"FAIL\", \"message\": \"处理失败\"}";
        }
        return null;
    }
}
